package cn.volunteer.points.system.service.impl;

import cn.volunteer.points.system.mapper.FileMapper;
import cn.volunteer.points.system.pojo.qo.FileQO;
import cn.volunteer.points.system.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @description:
 * @author:
 * @create: 创建时间：2021-04-16
 **/
@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Override
    public String uploadFile(MultipartFile file ) {

        String result = null ;

        String targetFilePath = null ;

        String fileResult = null ;

        // 2.设置文件名(UUID保证唯一)
        String fileName = UUID.randomUUID().toString().replace("-", "") + ".jpg";

        boolean systemType = getSystemType();

        if (systemType) {
             targetFilePath = "../dist/img/pic/";
             fileResult = "/img/pic/";
        }else{
            targetFilePath = "..\\dist\\img\\pic";
            fileResult = "\\img\\pic\\";
        }



        // 3.封装参数
        File targetFile = new File(targetFilePath + File.separator + fileName);

        FileOutputStream fileOutputStream = null ;



        try{
            fileOutputStream = new FileOutputStream(targetFile);
            IOUtils.copy(file.getInputStream(),fileOutputStream);
            log.info("文件上传成功，文件名：{},路径：{}",fileName,targetFile.toString());
            result = fileResult + fileName ;
        }catch (IOException e){
            throw new RuntimeException("文件上传失败！！！");
        }

        return result;
    }


    /**
     * 判断系统环境
     * @True：Linux
     * @false：Windows
     */
    private boolean getSystemType(){
        return System.getProperty("os.name").toLowerCase().contains("linux");
    }
}
